# -- coding: utf-8 --
import requests
from lxml import etree
import os
import time
import re


def get_url(url):
    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59",
    }
    response = requests.get(url, headers=headers)
    return response


def get_rank(url):
    response = get_url(url).text
    html = etree.HTML(response)
    href_list = html.xpath('//a[contains(@href, "/discover/toplist?id=")]/@href')
    rank_name_list = html.xpath('//a[contains(@href, "/discover/toplist?id=")]/text()')
    rank_name_list = [i for i in rank_name_list if i != '\n']
    href_list = [href_list[i] for i in range(len(href_list)) if i % 2 == 0]
    rank_dict = {}
    for i in range(len(href_list)):
        rank_url = url + '?' + href_list[i].split('?')[-1]
        rank_dict[str(i + 1)] = rank_name_list[i]
        rank_dict[rank_name_list[i]] = rank_url
    return rank_dict


def user_choice():
    print('-' * 100)
    print('网易云音乐榜单分类如下：')
    print('-' * 100)
    for i in range(int(len(rank_dict) / 2)):
        print(str(i + 1) + '.' + rank_dict[str(i + 1)], end='\t')
        if (i + 1) % 4 == 0:
            print()
    print()
    while True:
        choice = input('请输入要下载的榜单序号：（1-35）')
        if choice not in [str(i) for i in range(1, 36)]:
            print('输入错误，请重新输入')
            continue
        else:
            break
    print(f'正在下载 {choice}.{rank_dict[choice]} 音乐')
    return choice


def get_song(rank_url):
    response = get_url(rank_url).text
    html = etree.HTML(response)
    song_list = html.xpath('//a[contains(@href, "song?id=")]')[:100]
    p = r"[\/\\\:\*\?\"\<\>\|]"
    for data in song_list:
        href = data.xpath('./@href')[0]
        song_id = href.split('=')[1]
        try:
            song_title = data.xpath('./text()')[0]
        except:
            break
        song_title = re.sub(p, ' ', song_title)
        song_url = baseurl.format(song_id)
        if os.path.exists(song_title + '.mp3'):
            continue
        print(f'正在下载 {song_title}.mp3')
        song = get_url(song_url).content
        if song:
            with open(f'./{song_title}.mp3', 'wb') as f:
                f.write(song)
        time.sleep(0.5)


if __name__ == '__main__':
    url = 'https://music.163.com/discover/toplist'
    baseurl = 'http://music.163.com/song/media/outer/url?id={}'
    rank_dict = get_rank(url)
    choice = user_choice()
    rank_url = rank_dict[rank_dict[choice]]
    try:
        os.mkdir('./音乐')
    except:
        pass
    try:
        os.mkdir(f'./音乐/{rank_dict[choice]}')
    except:
        pass
    os.chdir(f'./音乐/{rank_dict[choice]}')
    get_song(rank_url)
    print('-' * 100)
    print('下载完成')
    print('-' * 100)
